package com.lnj.orders.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import jakarta.annotation.PostConstruct;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.lnj.utils.RedisKeys.ORDER_PAY_QRCODE;

@Component
@Log
public class AliPayUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //APPID
    @Value("${alipay.appId}")
    private  String APP_ID ;
    //应用私钥
    @Value("${alipay.privateKey}")
    private String APP_PRIVATE_KEY;
    //支付宝公钥
    @Value("${alipay.publicKey}")
    private String ALIPAY_PUBLIC_KEY;
    //支付宝网关
    @Value("${alipay.alipayGateway}")
    private String ALIPAY_GATEWAY;
    private final String FORMAT="JSON";
    private final String CHARSET="UTF-8";
    //签名类型
    @Value("${alipay.signType}")
    private String SIGN_TYPE;
    //支付宝异步通知地址
    @Value("${alipay.notifyUrl}")
    private String NOTIFY_URL;
    //支付宝同步通知地址
    @Value("${alipay.returnUrl}")
    private String RETURN_URL;
    private AlipayClient alipayClient = null;
    @PostConstruct
    public void init() {
        // 检查关键配置是否加载
        if (APP_PRIVATE_KEY == null || APP_PRIVATE_KEY.isEmpty()) {
            throw new IllegalStateException("支付宝私钥未正确配置");
        }

        alipayClient = new DefaultAlipayClient(
                ALIPAY_GATEWAY,
                APP_ID,
                APP_PRIVATE_KEY,
                FORMAT,
                CHARSET,
                ALIPAY_PUBLIC_KEY,
                SIGN_TYPE
        );
    }


    //生成支付二维码
    public String generateQRCodePay(String orderId, String totalPrice) {

        String redisKey = ORDER_PAY_QRCODE + orderId;
        String qrCode = stringRedisTemplate.opsForValue().get(redisKey);
        if (qrCode != null) {
            log.info("从Redis中获取到支付二维码，订单编号："+orderId);
            return qrCode;
        }

        log.info("生成支付二维码，订单编号："+orderId);
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl("你的异步通知地址");

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        bizContent.put("total_amount", totalPrice);
        bizContent.put("subject","订单支付");
        bizContent.put("qr_code_timeout_express","15m");//设置二维码过期时间

        request.setBizContent(bizContent.toString());

        int maxRetries = 3; // 最大重试次数
        int retryCount = 0;
        long retryInterval = 1000; // 重试间隔(毫秒)

        while (retryCount < maxRetries) {
            try {
                AlipayTradePrecreateResponse response = alipayClient.execute(request);
                if(response.isSuccess()){
                    //TODO:把二维码放入到Redis中
                     redisKey = ORDER_PAY_QRCODE + orderId;
                    //设置三十分钟过期
                    stringRedisTemplate.opsForValue().set(redisKey,response.getQrCode(),30, TimeUnit.MINUTES);
                    return response.getQrCode();
                } else {
                    retryCount++;
                    if (retryCount < maxRetries) {
                        Thread.sleep(retryInterval);
                        continue;
                    }
                    throw new RuntimeException("支付宝预创建失败: " + response.getSubMsg());
                }
            } catch (AlipayApiException e) {
                retryCount++;
                if (retryCount < maxRetries) {
                    try {
                        Thread.sleep(retryInterval);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                    }
                    continue;
                }
                throw new RuntimeException("支付宝接口调用异常(重试" + maxRetries + "次后失败)", e);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("重试过程中线程被中断", e);
            }
        }
        throw new RuntimeException("无法生成支付二维码");
    }

    //查询是否支付成功
    public boolean queryPayStatus(String orderId) {
        log.info("查询订单支付状态，订单编号："+orderId);
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);
        request.setBizContent(bizContent.toString());

        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            return response.isSuccess() &&
                    "TRADE_SUCCESS".equals(response.getTradeStatus());
        } catch (AlipayApiException e) {
            throw new RuntimeException("支付宝查询接口异常", e);
        }
    }

}
